const expresss = require("express")
const database = require("../database/connectDataBase")  // 用于连接数据库
const dataModel = require("../database/controlData") // 对数据表进行操作
const { linkrules } = require("../utils/validators")  // 导入校验规则
const { validationResult } = require('express-validator');  // 进行数据校验
const jwtverify = require("../utils/jwtverify")  //用户登录校验

const router = expresss.Router()

database(() => {
    // 查询文档数据
    router.get('/links', async (req, res) => {
        const { name, category, page = 1, limit = 10 } = req.query;

        let query = {};

        if (name) {
            query.name = { $regex: name, $options: 'i' };  // 模糊查询，忽略大小写
        }

        if (category) {
            query.category = category;  // 精确查询
        }

        try {
            const links = await dataModel.find(query)
                .skip((page - 1) * limit)
                .limit(parseInt(limit));

            const total = await dataModel.countDocuments(query);

            return res.status(200).json({
                errorCode: 0,
                msg: "查询成功",
                data: {
                    links,
                    total,
                    page: parseInt(page),
                    limit: parseInt(limit)
                }
            });
        } catch (err) {
            console.error('Error querying links:', err);
            return res.status(500).json({
                errorCode: 500,
                msg: "查询失败",
                data: null,
                errors: err.message
            });
        }
    });

    // 新增链接数据
    router.post('/link', linkrules, jwtverify, async (req, res) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errorCode: 400, msg: "数据校验失败", data: null, errors: errors.array() });
        }

        const { name, address, category, code } = req.body;

        try {
            const createdLink = await dataModel.create({ name, address, category, code });
            return res.status(200).json({
                errorCode: 0,
                msg: "增加成功",
                data: createdLink,
                errors: null
            });
        } catch (err) {
            console.error('Error creating link:', err);
            return res.status(200).json({
                errorCode: 400,
                msg: "增加失败",
                data: null,
                errors: err.message
            });
        }
    })

    // 删除连接数据
    router.delete('/link', jwtverify, async (req, res) => {
        const { id } = req.query; // 从查询参数中获取id
        try {
            if (!id) {
                throw new Error("缺少id查询参数");
            }

            console.log(`尝试删除ID为 ${id} 的链接`);

            const deleteResult = await dataModel.deleteOne({ _id: id });

            // 检查是否有文档被删除
            if (!deleteResult.deletedCount) {
                throw new Error("ID错误,没有匹配的项");
            }

            console.log(`ID为 ${id} 的链接删除成功`);
            return res.status(200).json({
                errorCode: 0,
                msg: "删除成功",
                data: deleteResult
            });
        } catch (err) {
            console.error(`删除连接时出错: ${err.message}`);
            return res.status(404).json({
                errorCode: 404,
                msg: "删除失败",
                data: null,
                errors: err.message
            });
        }
    });

    // 更新链接数据
    router.put('/link', linkrules, jwtverify, async (req, res) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({
                errorCode: 400,
                msg: "数据校验失败",
                data: null,
                errors: errors.array()
            });
        }

        const { id } = req.query;  // 从查询参数中获取 id
        const { name, address, category, code } = req.body;

        if (!id) {
            return res.status(400).json({
                errorCode: 400,
                msg: "缺少id查询参数",
                data: null,
                errors: null
            });
        }

        try {
            const updatedLink = await dataModel.findByIdAndUpdate(
                id,
                { name, address, category, code },  // 要更新的字段
                { new: true, runValidators: true } // 返回更新后的文档，并运行验证器
            );

            // 如果未找到要更新的文档
            if (!updatedLink) {
                return res.status(400).json({
                    errorCode: 400,
                    msg: "更新失败，ID错误，没有匹配的项",
                    data: null,
                    errors: null
                });
            }

            return res.status(200).json({
                errorCode: 0,
                msg: "更新成功",
                data: updatedLink,
                errors: null
            });
        } catch (err) {
            console.error('Error updating link:', err);
            return res.status(500).json({
                errorCode: 500,
                msg: "更新失败",
                data: null,
                errors: err.message
            });
        }
    });

    // 获取所有分类数据
    router.get('/categories', jwtverify, async (req, res) => {
        try {
            // 使用 MongoDB 的聚合功能来提取唯一的分类
            const categories = await dataModel.distinct('category');

            return res.status(200).json({
                errorCode: 0,
                msg: "获取分类数据成功",
                data: categories
            });
        } catch (err) {
            console.error('Error fetching categories:', err);
            return res.status(500).json({
                errorCode: 500,
                msg: "获取分类数据失败",
                data: null,
                errors: err.message
            });
        }
    });


    // 获取链接详情数据
    router.get('/link', jwtverify, async (req, res) => {
        const { id } = req.query;

        if (!id) {
            return res.status(400).json({
                errorCode: 400,
                msg: "缺少id查询参数",
                data: null,
                errors: null
            });
        }

        try {
            const link = await dataModel.findById(id, 'name address category code'); // 选择需要的字段

            if (!link) {
                return res.status(404).json({
                    errorCode: 404,
                    msg: "获取失败，ID错误，没有匹配的项",
                    data: null,
                    errors: null
                });
            }

            return res.status(200).json({
                errorCode: 0,
                msg: "获取详情成功",
                data: link,
                errors: null
            });
        } catch (err) {
            console.error('Error fetching link details:', err);
            return res.status(500).json({
                errorCode: 500,
                msg: "获取详情失败",
                data: null,
                errors: err.message
            });
        }
    });
}, () => { })

module.exports = router